﻿using Com.Lancetinc.Evs.Config;
using Com.Lancetinc.Evs.Events;
using Com.Lancetinc.Evs.Reports;
using Com.Lancetinc.Evs.ViewModels;
using Prism.Events;
using System.Windows;

namespace Com.Lancetinc.Evs.Controls
{
    /// <summary>
    /// 报告设置-报告模板预览
    /// </summary>
    public partial class ReportTemplateSettingPreviewUserControl
    {
        private readonly ReportConfig _rptConfig = AppConfigs.ReportConfig;
        private ReportViewModel _reportVm;
        public bool IsEmpty
        {
            get
            {
                if (!string.IsNullOrEmpty(_rptConfig.ReportTitle))
                {
                    return false;
                }

                if (!string.IsNullOrEmpty(_rptConfig.BannerFileName))
                    return false;

                return true;
            }
        }

        public ReportTemplateSettingPreviewUserControl()
        {
            InitializeComponent();
            this.Loaded += ReportTemplateSettingPreviewUserControl_Loaded;
            KnownAppEvents.ReportTemplatePreviewContentChanged.Subscribe(args =>
            {
                if (!this.IsVisible)
                    return;

                Preview();
            }, ThreadOption.UIThread);
        }

        private void ReportTemplateSettingPreviewUserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Preview();
        }

        public void Preview()
        {
            if (IsEmpty)
            {
                GridEmpty.Visibility = Visibility.Visible;
                GridPreview.Visibility = Visibility.Collapsed;
                return;
            }
            GridEmpty.Visibility = Visibility.Collapsed;
            GridPreview.Visibility = Visibility.Visible;
            ReportTemplateUserControl ctrlRpt = null;
            if (_reportVm == null)
            {
                _reportVm = CreateDummyReportInfo();
                ctrlRpt = new ReportTemplateUserControl();
                ctrlRpt.Setup(_reportVm);
                GridPreview.Children.Add(ctrlRpt);
            }
            else
            {
                ctrlRpt = GridPreview.Children[0] as ReportTemplateUserControl;
                ctrlRpt?.ReLoadBanner();
            }
        }

        public static ReportViewModel CreateDummyReportInfo()
        {
            var exper = ReportHelper.GetReportTemplateData();

            var expVm = new ExperViewModel(exper);
            var rptVm = new ReportViewModel(expVm);
            var previewImg = ReportHelper.GetIllustrationForTemplatePreview();
            for (int i = 0; i < 6; i++)
            {
                rptVm.Images.Add(previewImg);
            }

            return rptVm;
        }
    }
}